package org.redmagic.utils;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public final class Files {

    private static final Log LOG = LogFactory.getLog(Files.class);
    
    public static String toString(String filePath) throws IOException {
        return toString(new File(filePath));
    }
    
    public static String toString(File file) throws IOException {
        return toString(new FileInputStream(file));
    }
    
    public static String toString(InputStream inputStream) throws IOException {
        BufferedReader reader = null;
        
        try {
            reader = new BufferedReader(new InputStreamReader(inputStream));
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            return sb.toString();
        } finally {
            Closeables.closeQuietly(reader);
        }
    }
    
    public static boolean createQuietly(String uri) {
        return createQuietly(new File(uri));
    }
    
    public static boolean createQuietly(File file) {
        try {
            return create(file);
        } catch (IOException ioe) {
            LOG.warn("Unable to create file at: " + file.getAbsolutePath());
            return false;
        }
    }
    
    public static boolean create(String uri) throws IOException {
        return create(new File(uri));
    }
    
    public static boolean create(File file) throws IOException {
        if (!file.exists()) {
            if (!file.mkdirs()) {
                throw new IOException("Unable to create file at: " + file.getAbsolutePath());                    
            } else {
                file.getParentFile().mkdirs();
                if (!file.createNewFile()) {
                    throw new IOException("Unable to create file at: " + file.getAbsolutePath());
                } else {
                }
            }
        }
        return true;
    }
}